<template>
	<el-form ref="saveForm" class="save-form" label-position="left" label-width="80px" :model="activeAddress" :rules="rules">
        <el-form-item label="收货人" prop="accept_name">
            <el-input v-model="activeAddress.accept_name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="activeAddress.mobile"></el-input>
        </el-form-item>
        <el-form-item label="所在地区">
            <span @click="showAddressPicker">
                {{activeAddress.province_region ? activeAddress.province_region.name : '请选择地区' }}
                {{activeAddress.city_region ? activeAddress.city_region.name : ''}}
                {{activeAddress.area_region ? activeAddress.area_region.name : ''}}
            </span>
        </el-form-item>
		<el-form-item label="邮编" prop="zip">
            <el-input v-model="activeAddress.zip"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
            <el-input type="textarea" :rows="3" v-model="activeAddress.address"></el-input>
        </el-form-item>
        <el-form-item label="设为常用地址" label-width="100px">
            <el-switch
                v-model="activeAddress.is_default"
                on-text=""
                off-text=""
                on-color="#b21014"
                on-value="1"
                off-value="0">
            </el-switch>
        </el-form-item>

        <div class="buttons">
            <button @click.prevent="save" class="btn btn-block btn-normal">保存</button>
        </div>
    </el-form>
</template>

<script>
import api from '~/api/api.js';
import Picker from 'better-picker';

export default {
	props: {
		value: {
			type: Object,
			default: {

			}
		}
	},
    data () {
        return {
            activeAddress: Object.assign({}, this.value),
            // 地区滚轮选择器
            regionPicker: null,
            // 省份
            provinces: [

            ],
            cities: [],
            areas: [],
            rules: {
                accept_name: [
                    {required: true, message: '请输入收货人'},
                    {max:20, message: '收货人名称不能超过20个字符'},

                ],
                mobile: [
                    {required: true, message: '请输入手机号'},
                    {pattern: /^[0-9]+$/, message: '请输入正确的手机号', trigger: 'blur'}
                ],
                address: [
                    {required: true, message: '请输入详细地址'}
                ]
            }
        };
    },
    watch: {
        value (value) {
            console.log(value);
            this.activeAddress = value;
        }
    },
    created () {
        api.get('/region/index')
        .then(response => {
            this.provinces = response.data.regions;
            let provinces = [];
            this.provinces.forEach(function (item) {
                provinces.push({
                    text: item.name,
                    value: item.id
                });
            });
            this.regionPicker = new Picker({
                data: [
                    provinces,
                    [
                        {
                            text: '',
                            value: 0
                        }
                    ],
                    [
                        {
                            text: '',
                            value: 0
                        }
                    ]
                ],
                selectedIndex: [0,0,0],
                title: '地址选择'
            });

            this.regionPicker.on('picker.change', this.handleItemChange);
            this.regionPicker.on('picker.valuechange', (values, selectedIndex) => {
                if (values.length < 3) {
                    return this.$message.warning('请选择完整地区');
                }
                // 同步vue省市区数据
                let province = Object.assign({}, this.provinces[selectedIndex[0]]);
                this.activeAddress.province = province.id;
                this.activeAddress.province_region = province;

                let city = Object.assign({}, this.cities[selectedIndex[1]]);
                this.activeAddress.city = city.id;
                this.activeAddress.city_region = city;

                let area = Object.assign({}, this.areas[selectedIndex[2]])
                this.activeAddress.area = area.id;
                this.activeAddress.area_region = area;
                this.$forceUpdate();
            });
        });
    },
	methods: {
        // 显示选择器
        showAddressPicker () {
            let cIndex = 0;
            for (let index in this.provinces) {
                if (this.activeAddress.province && this.provinces[index].id == this.activeAddress.province) {
                    cIndex = index;
                    break;
                }
            }

            this.regionPicker.show(() => {
                this.regionPicker.scrollColumn(0, cIndex);
                this.getCities(cIndex)
                .then(response => {
                    let cIndex = 0;
                    if (!this.activeAddress.city) {
                        return 0;
                    }

                    for (let index in this.cities) {
                        if (this.cities[index].id == this.activeAddress.city) {
                            cIndex = index;
                            break;
                        }
                    }

                    this.regionPicker.scrollColumn(1, cIndex);

                    return cIndex;
                })
                .then(cIndex => {
                    this.getAreas(cIndex)
                    .then(response => {
                        let cIndex = 0;
                        if (!this.activeAddress.area) {
                            return ;
                        }

                        for (let index in this.areas) {
                            if (this.areas[index].id == this.activeAddress.area) {
                                cIndex = index;
                                break;
                            }
                        }

                        this.regionPicker.scrollColumn(2, cIndex);
                    });
                });
            });

        },
        // 动态加载市及区
        handleItemChange (index, selectedIndex) {
            switch (index) {
                case 0:
                    this.getCities(selectedIndex)
                    .then(response => {
                        this.getAreas(0);
                    });
                    break;
                case 1:
                    this.getAreas(selectedIndex);
                    break;
                default:
                    break;
            }
        },
        // 滚轮获取城市
        getCities (index) {
            let province = this.provinces[index];
            return api.get('/region/index/'+province.id)
            .then(response => {
                this.cities = response.data.regions;
                let cities = [];
                response.data.regions.forEach((item, index) => {
                    cities.push({
                        text: item.name,
                        value: item.id
                    });
                });
                this.regionPicker.refillColumn(1, cities);
                return response;
            });
        },
        // 滚轮获取地区
        getAreas (index) {
            let city = this.cities[index];
            return api.get('/region/index/'+city.id)
            .then(response => {
                this.areas = response.data.regions;
                let areas = [];
                response.data.regions.forEach((item, index) => {
                    areas.push({
                        text: item.name,
                        value: item.id
                    });
                });

                this.regionPicker.refillColumn(2, areas);

                return response;
            });
        },
        // 点击保存
        save () {
            this.$refs.saveForm.validate((valid) => {
                if (valid) {
                    this.$emit('input', this.activeAddress);
                    this.$emit('save', this.activeAddress);
                }
            });
        }
	}
}
</script>
